<template>
    <TopBar></TopBar>
    <div class="body">
        <div class="left">
            <div class="nav">
                <div class="logo">
                    <el-image src="https://zizi-1325809325.cos.ap-guangzhou.myqcloud.com/Retail/retail_logo.png"
                        fit="cover"></el-image>
                </div>
                <button @click="router.push('/retail')"><el-icon size="25" class="nav-icon">
                        <Histogram />
                    </el-icon>热门发现</button>
                <button @click="router.push('/retailSub')"><el-icon size="25" class="nav-icon">
                        <Promotion />
                    </el-icon>发布宝贝</button>
                <button @click="router.push('/retailNews')"><el-icon size="25" class="nav-icon">
                        <Comment />
                    </el-icon>我的通知</button>
                <button @click="jumpMyPage"><el-image class="my_avatar" :src="user.avatar"></el-image>我的页面</button>
            </div>
        </div>
        <div class="right">
            <!-- 帖子发布功能 -->
            <el-form :model="postForm" ref="postFormRef" label-width="80px">
                <div style="justify-content: center;align-items: center;display:flex">
                    <h1 style="margin: auto;">发布您的农产品</h1>
                </div>
                <el-form-item label="标题" prop="retailTitle"
                    :rules="[{ required: true, message: '请输入标题', trigger: 'blur' }]">
                    <el-input v-model="postForm.retailTitle" placeholder="请输入标题"></el-input>
                </el-form-item>
                <el-form-item label="内容" prop="retailContent"
                    :rules="[{ required: true, message: '请输入内容', trigger: 'blur' }]">
                    <el-input type="textarea" v-model="postForm.retailContent" placeholder="请输入内容" rows="4"></el-input>
                </el-form-item>
                <el-form-item label="图片" prop="retailImage"
                    :rules="[{ required: true, message: '请上传图片', trigger: 'change' }]">
                    <el-upload class="upload-demo" action="http://localhost:9090/files/uploadPost"
                        :on-success="handleImageSuccess" :before-upload="beforeImageUpload" :file-list="imageList"
                        :auto-upload="true">
                        <el-button size="small" type="primary">点击上传</el-button>
                    </el-upload>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="submitPost">发布</el-button>
                </el-form-item>
            </el-form>
            <div class="chat-container">
                <header class="chat-header">
                    <h1>农产品发布文案助手</h1>
                    <p>我是您的AI文案助手,基于Coze扣子AI大模型,可以帮助您构思、编辑和优化各种类型的农产品文案。请告诉我您需要什么样的帮助!</p>
                </header>
                <div class="chat-messages" ref="messagesContainer">
                    <div v-for="(message, index) in messages" :key="index" :class="['message', message.type]">
                        <div class="message-content">
                            <strong>{{ message.type === 'user' ? '您' : 'AI助手' }}:</strong>
                            {{ message.content }}
                        </div>
                    </div>
                    <div v-if="isTyping" class="message assistant">
                        <div class="message-content typing">
                            <strong>AI助手:</strong>
                            <span class="dot"></span>
                            <span class="dot"></span>
                            <span class="dot"></span>
                        </div>
                    </div>
                </div>
                <div class="chat-input">
                    <input v-model="userInput" @keyup.enter="sendMessage" placeholder="输入您的文案需求或问题..." />
                    <button @click="sendMessage">发送</button>
                </div>
            </div>
        </div>
    </div>
    <Footer></Footer>
</template>


<script setup>
import TopBar from '@/component/TopBar.vue'
import Footer from '@/component/Footer.vue'
import { nextTick } from 'vue';
import { ref, onMounted } from 'vue'
import { LazyImg, Waterfall } from "vue-waterfall-plugin-next";
import { useRoute } from "vue-router";
import router from '../../router/index.js'
// 在顶部导入图标
import { Picture } from '@element-plus/icons-vue'
import "vue-waterfall-plugin-next/dist/style.css";
import request from '../../utils/request';
import { ElNotification } from 'element-plus'

//优化卡片显示问题
const card_loading = ref(true);

// 响应式数据
const list = ref({})
const user = ref({});

//详情窗口bool值
const showDialog = ref(false)



const jumpMyPage = () => {
    if (!sessionStorage.getItem('uid')) {
        ElNotification({
            title: '失败',
            message: '请先登录',
            type: 'error',
        })
        setTimeout(() => {
            router.push('/login');
        }, 1000);
    }
    else {
        router.push('/retailMy')
    }
}

const getUserInfo = () => {
    const uid = sessionStorage.getItem('uid');
    if (uid) {
        const uidObj = JSON.parse(uid);
        request.get('/api/user/GetUserInfo', {
            params: {
                uid: uidObj
            }
        }).then(res => {
            user.value = res.data;
        }).catch(error => {
            console.error("请求失败", error);
        })
    } else {
        console.log("未登录");
        user.value.avatar = "https://bu.dusays.com/2024/12/28/677018da4485e.png";
    }
}

const postForm = ref({
    retailTitle: '',
    retailContent: '',
    retailImage: '',
    uid: JSON.parse(sessionStorage.getItem('uid')),
    retailTime: '',
    categoryUid: ''
});
const imageList = ref([]);

const handleImageSuccess = (response, file) => {
    postForm.value.retailImage = response.data; // 假设返回的数据中包含图片的URL
    imageList.value.push(file);
};

const beforeImageUpload = (file) => {
    const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJPG) {
        ElNotification({
            title: '错误',
            message: '只能上传 JPG 或 PNG 格式的图片',
            type: 'error',
        });
    }
    return isJPG;
};

const submitPost = async () => {
    console.log(postForm.value);
    if (!postForm.value.retailTitle || !postForm.value.retailContent || !postForm.value.retailImage) {
        ElNotification({
            title: '错误',
            message: '请填写完整的帖子信息',
            type: 'error',
        });
        return;
    }
    // 在此处添加提交表单的逻辑，例如调用 API
    postForm.value.retailTime = new Date().toLocaleString();
    console.log('提交的帖子信息:');
    console.log(postForm.value);

    await request.post('/api/retail/add', postForm.value).then(res => {
        console.log(res)
        // 提交成功后，清空表单
        postForm.value.retailTitle = '';
        postForm.value.retailContent = '';
        postForm.value.retailImage = '';
        imageList.value = [];
        ElNotification({
            title: '成功',
            message: '帖子发布成功',
            type: 'success',
        });
        router.push('/retail')
    })
};


// 初始化加载
onMounted(async () => {
    await getUserInfo();
})

const messages = ref([]);
const userInput = ref('');
const isTyping = ref(false);
const messagesContainer = ref(null);

const sendMessage = () => {
    if (userInput.value.trim() === '') return;

    messages.value.push({ type: 'user', content: userInput.value });
    request.post('/api/chatAI', {
        content: userInput.value
    }).then(res => {
        setTimeout(() => {
            streamResponse(res.data);
        }, 1000);
    })
    userInput.value = '';

    isTyping.value = true;
};

const streamResponse = (response) => {
    let i = 0;
    messages.value.push({ type: 'assistant', content: '' });
    const messageIndex = messages.value.length - 1;

    const intervalId = setInterval(() => {
        if (i < response.length) {
            messages.value[messageIndex].content += response[i];
            i++;
            nextTick(() => {
                scrollToBottom();
            });
        } else {
            clearInterval(intervalId);
            isTyping.value = false;
        }
    }, 50);
};

const scrollToBottom = () => {
    const container = messagesContainer.value;
    container.scrollTop = container.scrollHeight;
};

</script>

<style scoped>
.body {
    width: 100%;
    height: 100%;
    display: flex;
}

.left {
    width: 15%;
    height: 100%;
}

.nav {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    padding: 4vh;
    gap: 3vh;
    justify-content: center;
}

.nav button {
    font-size: large;
    font-weight: bold;
    transition: all 0.3s ease;
}

.nav button:hover {
    transform: scale(1.05);
}

.nav-icon {
    top: 0.7vh;
}


.logo {
    width: 50%;
}

.my_avatar {
    width: 3vh;
    top: 0.7vh;
    border-radius: 50%;
}

.right {
    width: 85%;
    height: 100%;
    background-color: #f4f4f4;
    padding: 20px;
    box-sizing: border-box;
}

.upload-demo i {
    font-size: 28px;
    color: #8c8c8c;
}

.chat-container {
    display: flex;
    flex-direction: column;
    height: 50vh;
    max-width: 800px;
    margin: 0 auto;
    border: 1px solid #e0e0e0;
    border-radius: 10px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    background-color: #f9f9f9;
}

.chat-header {
    background-color: #4a90e2;
    color: white;
    padding: 20px;
    border-top-left-radius: 10px;
    border-top-right-radius: 10px;
}

.chat-header h1 {
    margin: 0;
    font-size: 24px;
}

.chat-header p {
    margin: 10px 0 0;
    font-size: 14px;
    opacity: 0.8;
}

.chat-messages {
    flex-grow: 1;
    overflow-y: auto;
    padding: 20px;
    background-color: white;
}

.message {
    margin-bottom: 15px;
    padding: 10px 15px;
    border-radius: 20px;
    max-width: 80%;
    line-height: 1.4;
}

.user {
    background-color: #e7f4ff;
    color: #333;
    align-self: flex-end;
    margin-left: auto;
}

.assistant {
    background-color: #f0f0f0;
    color: #333;
    align-self: flex-start;
}

.chat-input {
    display: flex;
    padding: 15px;
    background-color: white;
    border-top: 1px solid #e0e0e0;
}

input {
    flex-grow: 1;
    padding: 10px 15px;
    border: 1px solid #ccc;
    border-radius: 20px;
    font-size: 16px;
}

.chat-container button {
    padding: 10px 20px;
    background-color: #4a90e2;
    color: white;
    border: none;
    border-radius: 20px;
    margin-left: 10px;
    cursor: pointer;
    font-size: 16px;
    transition: background-color 0.3s;
}

.chat-container button:hover {
    background-color: #3a7bc8;
}

.typing {
    display: flex;
    align-items: center;
}

.dot {
    width: 8px;
    height: 8px;
    background-color: #333;
    border-radius: 50%;
    margin: 0 3px;
    animation: bounce 1.4s infinite ease-in-out both;
}

.dot:nth-child(1) {
    animation-delay: -0.32s;
}

.dot:nth-child(2) {
    animation-delay: -0.16s;
}

@keyframes bounce {

    0%,
    80%,
    100% {
        transform: scale(0);
    }

    40% {
        transform: scale(1);
    }
}
</style>